package lock.lntelligence.gjx.activity;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.aiton.administrator.shane_library.shane.ZjbBaseActivity;
import com.aiton.administrator.shane_library.shane.utils.ACache;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import lock.lntelligence.gjx.R;
import lock.lntelligence.gjx.constant.Constant;
import lock.lntelligence.gjx.model.BluetoothDeviceInfo;
import lock.lntelligence.gjx.model.User;

public class MainActivity extends ZjbBaseActivity implements View.OnClickListener {

    private DrawerLayout drawer_layout;
    private LinearLayout list_left_drawer;
    private BluetoothAdapter mMBluetoothAdapter;
    private List<BluetoothDeviceInfo> mBluetoothDeviceList = new ArrayList<>();
    private boolean isSleep =false;
    private boolean isNotSleep = true ;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            String action = intent.getAction();
            // 获得已经搜索到的蓝牙设备
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.e("onReceive ", "扫描中");
                // 搜索到的不是已经绑定的蓝牙设备
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    String address = device.getAddress();
                    Log.e("onReceive ", "设备名称" + device.getName() + "\n设备地址" + address);
                    String name = device.getName();
                    mBluetoothDeviceList.add(new BluetoothDeviceInfo(name, address));
                    mBluetoothAdapter.notifyDataSetChanged();
                }
                // 搜索完成
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                Log.e("onReceive ", "扫描完成 ");
                mBluetoothAdapter.notifyDataSetChanged();
                mProgressDialogScan.dismiss();
            }
        }
    };
    private ListView mListView_device;
    private MyAdapter mBluetoothAdapter;
    private ProgressDialog mProgressDialogScan;
    private TextView mTextView_phone;
    private User mUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        init();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void initData() {
        ACache aCache = ACache.get(MainActivity.this);
        mUser = (User) aCache.getAsObject(Constant.ACACHE.USER);
        //初始化一个数据
        mBluetoothDeviceList.add(new BluetoothDeviceInfo("A栋一单元",  "D8:9A:34:15:F5:73"));
    }

    @Override
    protected void initViews() {
        mBluetoothAdapter = new MyAdapter();
        mListView_device.setAdapter(mBluetoothAdapter);
        mTextView_phone.setText(mUser.getContains().getPhone());
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_mine).setOnClickListener(this);
        findViewById(R.id.button_scan).setOnClickListener(this);
        findViewById(R.id.rela_exit).setOnClickListener(this);
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {

    }

    @Override
    protected void findID() {
        drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
        list_left_drawer = (LinearLayout) findViewById(R.id.list_left_drawer);
        mListView_device = (ListView) findViewById(R.id.listView_device);
        mTextView_phone = (TextView) findViewById(R.id.textView_phone);
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mBluetoothDeviceList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View inflate = getLayoutInflater().inflate(R.layout.lisetitem_device, null);
            TextView textView_deviceName = (TextView) inflate.findViewById(R.id.textView_deviceName);
            TextView textView_deviceAdd = (TextView) inflate.findViewById(R.id.textView_deviceAdd);
            inflate.findViewById(R.id.button_do).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this,DoActivity.class);
                    isNotSleep=false;
                    startActivity(intent);
                }
            });
            if (mBluetoothDeviceList.size() > 0) {
                textView_deviceName.setText(mBluetoothDeviceList.get(position).getBluetoothName());
                textView_deviceAdd.setText(mBluetoothDeviceList.get(position).getBluetoothAddress());
            }
            return inflate;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_RESULT.REQUEST_OPEN_BT_CODE && resultCode == Constant.REQUEST_RESULT.REQUEST_OPEN_BT_CODE) {
            startScan();
        }else if(requestCode == Constant.REQUEST_RESULT.IS_SLEEP && resultCode == Constant.REQUEST_RESULT.IS_SLEEP){
            isSleep = false;
        }
    }

    private void startScan() {
        mMBluetoothAdapter.startDiscovery();
        mProgressDialogScan = new ProgressDialog(MainActivity.this);
        mProgressDialogScan.setMessage("查找设备……");
        mProgressDialogScan.setCancelable(false);
        mProgressDialogScan.show();
        mProgressDialogScan.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    mMBluetoothAdapter.cancelDiscovery();
                    mProgressDialogScan.dismiss();
                }
                return false;
            }
        });
        Log.e("startScan ", "开始扫描");
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 注册用以接收到已搜索到的蓝牙设备的receiver
        IntentFilter mFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, mFilter);
        // 注册搜索完时的receiver
        mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, mFilter);
        isNotSleep = true ;
        if (isSleep){
            Intent intent = new Intent();
            intent.setClass(MainActivity.this,LockActivity.class);
            intent.putExtra("sleep","sleep");
            startActivityForResultTo(intent,Constant.REQUEST_RESULT.IS_SLEEP);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isNotSleep) {
            isSleep = true;
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        //解除注册
        unregisterReceiver(mReceiver);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rela_exit:
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("确认退出？")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                ACache aCache = ACache.get(MainActivity.this);
                                aCache.clear();
                                finish();
                                Intent intent = new Intent();
                                intent.setClass(MainActivity.this,LoginActivity.class);
                                isNotSleep=false;
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        })
                        .show();
                break;
            case R.id.imageView_mine:
                drawer_layout.openDrawer(list_left_drawer);
                break;
            case R.id.button_scan:
                //得到BluetoothAdapter对象
                mMBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                //判断BluetoothAdapter对象是否为空，如果为空，则表明本机没有蓝牙设备
                if (mMBluetoothAdapter != null) {
                    System.out.println("本机拥有蓝牙设备");
                    Log.e("onClick ", "本机拥有蓝牙设备");
                    //调用isEnabled()方法判断当前蓝牙设备是否可用
                    if (!mMBluetoothAdapter.isEnabled()) {
                        //如果蓝牙设备不可用的话,创建一个intent对象,该对象用于启动一个Activity,提示用户启动蓝牙适配器
                        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(intent, Constant.REQUEST_RESULT.REQUEST_OPEN_BT_CODE);
                    } else {
                        mBluetoothDeviceList.clear();
                        //得到所有已经配对的蓝牙适配器对象
                        Set<BluetoothDevice> devices = mMBluetoothAdapter.getBondedDevices();
                        if (devices.size() > 0) {
                            //用迭代
                            for (Iterator iterator = devices.iterator(); iterator.hasNext(); ) {
                                //得到BluetoothDevice对象,也就是说得到配对的蓝牙适配器
                                BluetoothDevice device = (BluetoothDevice) iterator.next();
                                //得到远程蓝牙设备的地址
                                Log.e("onClick ", "蓝牙地址：" + device.getAddress() + "");
                                mBluetoothDeviceList.add(new BluetoothDeviceInfo(device.getName(),device.getAddress()));
                                mBluetoothAdapter.notifyDataSetChanged();
                            }
                        }
                        startScan();
                    }

                } else {
                    Log.e("onClick ", "没有蓝牙设备");
                }

                break;
        }
    }
}
